#!/bin/bash
set -Eeuo pipefail

# 初始化管理员
USER='admin'
PASSWORD='admin@gtinlian'

# 处理器架构检测
ARCH=`uname -m`
NODE_PACKAGE_NAME=`( [ ${ARCH} == "x86_64" ] && echo "node-v18.20.3-linux-x64" ) || echo "node-v18.20.3-linux-arm64"`

#centos7 环境配置
function centOS_install(){
  yum -y update
  yum -y install elrepo-release
  yum -y install python3          # 项目使用python 3 开发
  yum -y install libvirt          # libvirt 管理服务 
  yum -y install qemu-kvm         # key 环境
  yum -y install qemu-img         # kvm 环境管理磁盘
  yum install -y libvirt-devel       # libvirt-python 依赖
  yum -y install mariadb-devel      # mysqlclient 依赖
  yum -y install gcc gcc-c++
  yum -y install wget

  # 依赖配置
  echo 'asgiref==3.4.1
    certifi==2024.2.2
    charset-normalizer==2.0.12
    Django==3.2.25
    idna==3.6
    libvirt-python==10.2.0
    mysqlclient==2.1.1
    pytz==2024.1
    requests==2.27.1
    sqlparse==0.4.4
    typing_extensions==4.1.1
    opencv-python>=4.10.0.82
    django-apscheduler==0.6.2
    urllib3==1.26.18' | sed 's/\  //g' > /tmp/requirement.txt
    

  python3 -m venv .env
  . .env/bin/activate
  # 更新pip
  pip install --upgrade pip
  pip install -r /tmp/requirement.txt -i https://mirrors.aliyun.com/pypi/simple

  wget https://nodejs.org/dist/v16.20.2/node-v16.20.2-linux-x64.tar.xz
  tar -xf node-v16.20.2-linux-x64.tar.xz
  cat /etc/profile |grep 'node-v16.20.2-linux-x64' &>/dev/null || echo 'export PATH=${PATH}:'`pwd`/node-v16.20.2-linux-x64/bin >> /etc/profile
}

function ubuntu_install(){
  #第一个参数等于2默认使用系统自带的node和npm版本
  NODE_PACKAGE=${1:-2}
  export DEBIAN_FRONTEND=noninteractive
  apt-get update
  apt-get -q -y install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils \
    gcc g++ make libssh-dev libpcre3-dev `[ ${NODE_PACKAGE} -eq 2 ] && echo nodejs npm`\
    python3-venv libvirt-dev libmysqlclient-dev python3-dev mysql-server redis-server adb

  # 配置redis密码
  grep 'd166be68-ed5e-4689-890f-ec4df6aee4ad' /etc/redis/redis.conf > /dev/null ||  
  echo "requirepass 'd166be68-ed5e-4689-890f-ec4df6aee4ad'" >> /etc/redis/redis.conf
  systemctl restart redis

  # 数据库用户初始化
  echo "select user from mysql.user where user = 'gtinlian'" | mysql |grep 'gtinlian' &> /dev/null \
  || echo -e "
  create user gtinlian@'localhost';
  grant all on *.* to gtinlian@'localhost';
    alter user gtinlian@'localhost' identified by 'd166be68-ed5e-4689-890f-ec4df6aee4ad';
  " | mysql
  echo 'show databases;' | mysql | grep 'GTLVM' &> /dev/null \
  || echo 'create database GTLVM default charset=utf8;' | mysql

  # python 项目编译初始化
  echo 'Django==5.0.1
    sqlparse==0.4.4
    libvirt-python==9.10.0
    mysqlclient==2.2.1
    requests==2.31.0
    opencv-python>=4.10.0.82
    django-redis==5.4.0
    django-apscheduler==0.6.2
    django-redis==5.4.0
    ' | sed 's/^\    //g' > /tmp/requirement.txt
  python3 -m venv .env
  . .env/bin/activate
  pip install --upgrade pip
  pip install -r /tmp/requirement.txt -i https://mirrors.aliyun.com/pypi/simple
  rm -rf /tmp/requirement.txt
  python3 gtlvm-api/run.py makemigrations application
  python3 gtlvm-api/run.py makemigrations virtapp
  python3 gtlvm-api/run.py migrate
  echo -e "
    from application.models import User
    u = ((lambda u: u[0] if len(u) > 0 else User())(User.objects.filter(username=\"${USER}\")))
    u.username = 'admin'
    u.set_password(\"${PASSWORD}\")
    u.email = 'gtinlian@sina.com'
    u.save()
  " | sed 's/\  //g' | python3 gtlvm-api/run.py shell 

  # nginx 代理和静态环境部署
  [ -d nginx ] || ./nginx-1.22.1/install.sh

    # 安装18.20.3 版本的node
  [ ${NODE_PACKAGE} -eq 2 ] || 
  ( [ -f ${NODE_PACKAGE_NAME}.tar.xz ] || curl -fsSLO https://nodejs.org/dist/v18.20.3/${NODE_PACKAGE_NAME}.tar.xz ) && 
  ( [ -d ${NODE_PACKAGE_NAME} ] || tar -xf ${NODE_PACKAGE_NAME}.tar.xz ) && 
  export PATH="${PATH}:`pwd`/${NODE_PACKAGE_NAME}/bin"

  bash -c "cd gtlvm-web && npm install && npm run build"
  bash -c "cd ws-scrcpy && npm install && npm run dist"
  
}

function install_prod(){
  . .env/bin/activate
  OUT_PATH=${1:-prod}
  [ -d ${OUT_PATH} ] || mkdir ${OUT_PATH}

  # 使用本地的nodejs
  [ -d ${NODE_PACKAGE_NAME} ] && cp -rp ${NODE_PACKAGE_NAME} ${OUT_PATH}
  export PATH="`pwd`/${OUT_PATH}/${NODE_PACKAGE_NAME}/bin:${PATH}"
  python -m compileall gtlvm-api websockify
  for i in ` find gtlvm-api websockify  -name "__pycache__"`; 
  do
    mkdir -p ${OUT_PATH}/${i:0:-11}
    mv $i/*  ${OUT_PATH}/${i:0:-11}
  done
  for i in `find ${OUT_PATH} -name "*.pyc" `
  do 
    mv $i ${i:0:-15}pyc;
  done
  cp -rp .env ${OUT_PATH}
  cp -rp nginx ${OUT_PATH}
  cp -rp ws-scrcpy/dist ${OUT_PATH}/ws-scrcpy
  echo 'cd prod/ws-scrcpy/ && npm install ' | bash
  cp -rp start.sh  ${OUT_PATH}/start.sh
  sed -i 's/\.py/\.pyc/g' ${OUT_PATH}/start.sh
  sed -i 's/dist\/index.js/index.js/g' ${OUT_PATH}/start.sh
  . .env/bin/activate.csh
}

case ${1:-} in
  web)  
    [ -d nginx/html/ ] || rm -rf nginx/html/
    [ -d ${NODE_PACKAGE_NAME} ] && export PATH=`pwd`/${NODE_PACKAGE_NAME}/bin/:${PATH}
    bash -c " cd gtlvm-web && npm install && npm run build"
  ;;
  migrate)
    python3 gtlvm-api/run.py makemigrations $2
    python3 gtlvm-api/run.py migrate
    ;;
  build)
    # 根据系统进行环境搭建
    case $(sed '$a echo ${PRETTY_NAME}' /etc/os-release  | sh) in 
      'Ubuntu 23.04')
       	ubuntu_install
       ;;
      'Ubuntu 22.04.4 LTS')
        ubuntu_install 1
      ;;
      'Ubuntu 22.04.2 LTS')
        ubuntu_install 1
      ;;
      'CentOS Linux 7 (Core)')
        centOS_install
      ;;
    esac
  ;;
  install)
    install_prod ${2:-prod}
  ;;
  *)
    echo -e "
    install option
    option:
        web             编译前端项目
        migrate [app]   数据库迁移
        build           构建项目
        install  [path: default prod]       安装
        "
  ;;
esac